<template>
  <div class="view-request-form">
    <el-container>
      <el-header class="form-header" height="22">
        <div class="header-text">View Request Form</div>
      </el-header>
      <el-main class="container-main">
        <el-form>

          <status-management
            ref="statusManagementData"
            :statusManagementData.sync="statusManagementData"
            :functionList="functionList">
          </status-management>

          <submission-detail
            ref="submissionDetail"
            :functionList="functionList"
            :submissionDetailData.sync="submissionDetailData"
            :compareChangeRequirementData="changeRequirementData">
          </submission-detail>

          <change-requirement
            ref="changeRequirement"
            class="form-padding"
            :compareStatusManagementData="statusManagementData"
            :functionList="functionList"
            :compareSubmissionDetailData="submissionDetailData"
            :changeRequirementData.sync="changeRequirementData">
          </change-requirement>

          <risk-assessment-review-result
            ref="riskAssessmentReviewResult"
            class="form-padding"
            :functionList="functionList"
            :changeRequirementData="changeRequirementData"
            :riskAssessmentReviewData.sync="riskAssessmentReviewData">
          </risk-assessment-review-result>

          <task-form
            ref="taskForm"
            class="form-padding"
            :compareStatusManagementData="statusManagementData"
            :functionList.sync="functionList"
            :taskFormData.sync="taskFormData"
            :changeRequirementData="changeRequirementData">
          </task-form>

          <supplementary-information
            ref="supplementary"
            class="form-padding"
            :functionList="functionList"
            :supplementaryData.sync="supplementaryData"
            :changeRequirementData="changeRequirementData">
          </supplementary-information>

          <attachment-upload
            ref="attachmentUpload"
            class="form-padding"
            :functionList="functionList"
            :uploadUrl="uploadUrl"
            :downloadUrl="downloadUrl"
            :acceptFileType="acceptFileType"
            :fileSizeLimit="fileSizeLimit">
          </attachment-upload>

          <change-control-teams-reference
            ref="changeControlTeamsReference"
            class="form-padding"
            :functionList="functionList"
            :changeControlTeamsReferenceData.sync="changeControlTeamsReferenceData">
          </change-control-teams-reference>

          <conversation-history
            :functionList="functionList"
            :downloadUrl="downloadUrl"
            :conversationHistoryData="conversationHistoryData"
            class="form-padding">
          </conversation-history>

          <el-form-item class="submit-form">
            <el-button @click="updateAction">Update</el-button>
            <el-button v-show="functionList.endorse_reject" @click="endorseAction">Endorse</el-button>
            <el-button v-show="functionList.withdraw" @click="withdrawAction">Withdraw</el-button>
            <el-button @click="replyAction">Reply</el-button>
            <el-button @click="cancelAction">Cancel</el-button>
            <el-button v-show="functionList.review_reject" @click="reviewAction">Review</el-button>
            <el-button v-show="functionList.waiting_reject" @click="waitingAction">Wait Fot Other Action</el-button>
            <el-button v-show="functionList.pending_reject" @click="pendingAction">Pending</el-button>
            <el-button v-show="functionList.endorse_reject" @click="rejectAction">Reject</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
    <reply-form ref="replyForm" :formBaseData="formBaseData" :functionList="functionList"
                @refreshConversationHistory="refreshConversationHistory"></reply-form>
  </div>
</template>

<script>
import constants from '@/common/js/constants'
import userService from '@/service/user'
import submissionDetail from './form-modules/SubmissionDetail.vue'
import changeRequirement from './form-modules/ChangeRequirement.vue'
import { parseRequestFormData, createRequestFormMapping } from '@/common/js/requestForm'
import requestFormService from '@/service/requestForm'
import authenticationService from '@/service/authentication'
import taskForm from './form-modules/TaskForm'
import supplementaryInformation from './form-modules/SupplementaryInformation.vue'
import attachmentUpload from '@/base-components/attachment-upload/AttachmentUpload.vue'
import replyForm from './form-modules/ReplyForm.vue'
import moment from 'moment'
import conversationHistory from './form-modules/ConversationHistory.vue'
import riskAssessmentReviewResult from './form-modules/RiskAssessmentReviewResult.vue'
import changeControlTeamsReference from './form-modules/ChangeControlTeamsReference.vue'
import requestRemarksService from '@/service/requestRemarks'
import statusManagement from './form-modules/StatusManagement.vue'
import _ from 'lodash'
import Bus from '@/common/js/eventBus'

export default {
  name: 'ChangeRequestForm',
  components: {
    submissionDetail,
    changeRequirement,
    riskAssessmentReviewResult,
    taskForm,
    supplementaryInformation,
    attachmentUpload,
    replyForm,
    conversationHistory,
    changeControlTeamsReference,
    statusManagement
  },
  data() {
    return {
      isLoading: true,
      statusManagementData: {
        pcrsStatusValue: '',
        inCharge: ''
      },
      formBaseData: {},
      changeRequirementData: {
        changeMainCategory: '',
        changeMainCategoryList: [],
        changeSubCategory: '',
        changeSubCategoryList: [],
        productionPlatformInvolve: '',
        expectedDateChange: '',
        expectedTimeChange: {
          hours: '',
          minutes: '00'
        },
        secAdminReference: '',
        onlineServiceImpact: {
          fromDate: '',
          toDate: '',
          description: ''
        },
        isOnlineService: 'No',
        backendApplicationFunctionImpactDescription: '',
        isBackendApplication: 'No',
        systemPlatformImpactDescription: '',
        isSystemPlatform: 'No',
        // linco
        isRiskLevel: false,
        riskLevel: '',
        riskAssessment: ''
      },
      riskAssessmentReviewData: {
        riskAssessmentReviewResult: '',
        riskAssessmentRemark: '',
        riskAssessmentProgress: ''
      },
      submissionDetailData: {
        user: {
          requesterDomainId: '',
          requesterDisplayName: '',
          phone: '',
          email: ''
        },
        TTNo: '',
        splitedTTNos: [], // not need to deliver it to backend -- Mike Xie
        typeOfChange: '',
        classificationOfChange: '',
        ttPRLevel: '',
        endorserTeamId: {},
        endorserArray: [],
        changeMainCategory: '',
        changeMainCategoryList: [],
        changeSubCategory: '',
        changeSubCategoryList: [],
        TTOrPRLevel: '',
        relatedPCRS: '',
        splitedPCRS: [],
        copyTo: '',
        changeObjective: '',
        currentDateTime: moment(new Date()).format('DD-MMM-YYYY HH:mm')
      },
      taskFormData: {
        txt1stVerifierDomain: '',
        txt1stContactNumber: '',
        txt2ndVerifierDomain: '',
        txt2ndContactNumber: '',
        dateVerificationDeadline: '',
        workDuration: '',
        requestprocedures: [
          {
            'procedureType': 'Working',
            'procedureSeq': '',
            'procedureDesc': '',
            'handledBy': '',
            'contactNo': '',
            'taskStatus': '',
            'taskRemark': ''
          },
          {
            'procedureType': 'Recovery',
            'procedureSeq': '',
            'procedureDesc': '',
            'handledBy': '',
            'contactNo': '',
            'taskStatus': '',
            'taskRemark': ''
          },
          {
            'procedureType': 'Verify',
            'procedureSeq': '',
            'procedureDesc': '',
            'handledBy': '',
            'contactNo': '',
            'taskStatus': '',
            'taskRemark': ''
          }
        ],
        verifyDuration: '',
        recoveryDuration: '',
        isRequireFallback: false,
        is1stMoreThanOneParty: false,
        is2ndMoreThanOneParty: false,
        noFallbackActionReason: ''
      },
      supplementaryData: {
        qaTestResult: '',
        approveQATestResult: '',
        ppTestResult: '',
        approvePPRunResult: '',
        testEnvironment: ''
      },
      attachments: [],
      changeControlTeamsReferenceData: {
        chgCtlRef: ''
      },
      conversationHistoryData: [{
        sender: '',
        receiver: '',
        description: '',
        createdAt: '',
        attachmentList: []
      }],
      dialogReplyFormVisible: false,
      functionList: {},
      uploadUrl: '/rest/attachment/upload',
      downloadUrl: '/rest/attachment/download',
      acceptFileType: 'jpg,gif,png,bmp,doc,txt,pdf,docx,xls,xlsx,zip,msg,rtf,tif,html,htm,rar',
      fileSizeLimit: 1024
    }
  },
  async created() {
    let load = this.$loading()
    try {
      await this.initFormData(this.$route.params.id)
      await this.initFunctionList(this.$route.params.id)
      await this.initConversationHistory(this.$route.params.id)
      await this.initBusEvents()
    } catch (error) {
      load.close()
    }
    load.close()
  },
  beforeDestroy() {
    this.removeBusEvents()
  },
  methods: {
    updateAction() {
      this.submitForm()
    },
    endorseAction() {
      if (this.endorseValidate()) {
        this.formBaseData.endorsedBy = userService.getUser().requesterDomainId
        this.statusManagementData.pcrsStatusValue = constants.PCRS_STATUS.ENDORSED
        this.statusManagementData.requestType = constants.PCRS_STATUS.ENDORSED
        this.submitForm()
      } else {
        this.$message.error('PP or QA test result should be approved')
      }
    },
    endorseValidate() {
      let valid = true
      if (this.supplementaryData.qaTestResult === constants.TEST_RESULT.NO_QA_UAT_TESTING && this.supplementaryData.approveQATestResult !== 'Yes') {
        valid = false
      }
      if (this.supplementaryData.ppTestResult === constants.TEST_RESULT.NO_PP_TESTING && this.supplementaryData.approvePPRunResult !== 'Yes') {
        valid = false
      }
      return valid
    },
    withdrawAction() {
      this.$confirm('Are you sure to Withdraw PCRS?', 'Notice', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        this.statusManagementData.pcrsStatusValue = constants.PCRS_STATUS.WITHDRAWN
        this.statusManagementData.requestType = constants.PCRS_STATUS.WITHDRAWN
        this.submitForm()
      })
    },
    replyAction() {
      this.$refs.replyForm.popWindow()
    },
    cancelAction() {
      window.close()
    },
    rejectAction() {
      this.$confirm('Are you sure to Reject PCRS?', 'Notice', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        this.statusManagementData.pcrsStatusValue = constants.PCRS_STATUS.REJECTED
        this.statusManagementData.requestType = constants.PCRS_STATUS.REJECTED
        this.submitForm()
      })
    },
    reviewAction() {
      this.statusManagementData.pcrsStatusValue = constants.PCRS_STATUS.REVIEWED
      this.statusManagementData.requestType = constants.PCRS_STATUS.REVIEWED
      this.submitForm()
    },
    waitingAction() {
      this.statusManagementData.pcrsStatusValue = constants.PCRS_STATUS.WAITING_FOR_PP
      this.statusManagementData.requestType = constants.PCRS_STATUS.WAITING_FOR_PP
      this.submitForm()
    },
    pendingAction() {
      this.$confirm('Are you sure to Reject PCRS?', 'Notice', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        this.statusManagementData.pcrsStatusValue = constants.PCRS_STATUS.PENDING
        this.statusManagementData.requestType = constants.PCRS_STATUS.PENDING
        this.submitForm()
      })
    },
    refreshConversationHistory(value) {
      this.initConversationHistory(this.$route.params.id)
    },
    submitForm() {
      let refsList = ['submissionDetail', 'changeRequirement', 'taskForm', 'supplementary', 'attachmentUpload']
      let $this = this

      refsList.forEach((moduleName) => {
        this.$refs[moduleName].$refs['validatorForm'].validate((valid) => {
        })
      })
      setTimeout(async () => {
        // Check whether the page has css: el-icon-circle-close attributes
        let hasError = $this.$el.innerHTML.includes('el-form-item is-error')
        if (!hasError && $this.$refs['taskForm'].validateProcedureEditTable()) {
          const loading = this.$loading()
          this.attachments = this.$refs['attachmentUpload'].getAttachments()
          this.taskFormData.requestprocedures = $this.$refs['taskForm'].getRequestProcedureData()
          let postData = createRequestFormMapping(this.formBaseData, this.submissionDetailData, this.changeRequirementData,
            this.taskFormData, this.supplementaryData, this.attachments, this.statusManagementData, this.riskAssessmentReviewData)
          let responseData = await requestFormService.updateRequestForm(postData)
          if (responseData.refNO) {
            $this.$alert(`Update Success, Ref No: ${responseData.refNO}`, {
              confirmButtonText: 'Close'
            }).then(_ => {
              // window.close()
            }).catch(_ => {})
          }
          loading.close()
        } else {
          this.$message({showClose: true, message: 'Missing Some Data Input', type: 'error'})
        }
      }, 200)
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    onPopUpReplyForm() {
      this.$refs.replyForm.popWindow()
    },
    initBusEvents() {
      Bus.$on('validateTypeOfChange', () => {
        this.$refs['submissionDetail'].$refs['validatorForm'].validateField('typeOfChange')
      })
      Bus.$on('validateExpectedDateChange', () => {
        this.$refs['changeRequirement'].$refs['validatorForm'].validateField('expectedDateChange')
      })
    },
    removeBusEvents() {
      Bus.$off('validateTypeOfChange')
      Bus.$off('validateExpectedDateChange')
    },
    async initFormData() {
      let responseData = await requestFormService.searchSubmissionForm(this.$route.params.id)
      let formData = parseRequestFormData(responseData)
      this.$refs['attachmentUpload'].setAttachments(formData.attachments)
      this.formBaseData = formData.formBaseData
      this.submissionDetailData = formData.submissionDetailData
      this.changeRequirementData = formData.changeRequirementData
      this.taskFormData = formData.taskFormData
      this.supplementaryData = formData.supplementaryData
      this.statusManagementData = formData.statusManagementData
      this.riskAssessmentReviewData = formData.riskAssessmentReviewData
    },
    async initFunctionList(refNo) {
      this.functionList = await authenticationService.getFunctionListByFormNo(refNo)
    },
    async initConversationHistory(refNo) {
      let conversationHistory = await requestRemarksService.getRequestRemarksByRefNo(refNo)
      this.conversationHistoryData = _.sortBy(conversationHistory, function (item) {
        return -item.id
      })
    }
  }
}
</script>

<style scoped lang="scss">
  @import './../../common/css/base.scss';

  .view-request-form {
    margin: 10px;
  }

  .container-main {
    border: 1px solid $base-header-color;
  }

  .submit-form {
    margin-top: 20px;
    text-align: center;
  }

  .form-header {
    font-size: 18px;
    @include baseHeader(35px)
  }

  .header-text {
    color: #fff;
    margin-top: 5px;
    font-weight: bold;
  }

  .form-padding {
    margin-top: 10px;
  }

  .el-form-item {
    margin-bottom: 10px;
  }

  .change-request-form {
    border: 1px solid $base-header-color;
  }
</style>
